package com.jin.webvideo.config;

import com.google.common.cache.CacheBuilder;
import com.jin.webvideo.config.filter.GroupFilter;
import com.jin.webvideo.config.filter.TraceFilter;
import com.jin.webvideo.config.filter.AccessFilter;
import com.jin.webvideo.config.filter.access.handler.InetAddressAccessHandler;
import com.jin.webvideo.config.filter.access.handler.UserAccessHandler;
import com.jin.webvideo.util.SimpleTemplateParser;
import com.jin.webvideo.util.base.DateUtil;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;

import javax.servlet.Filter;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Configuration
public class FilterConfig {
    @Bean
    public SimpleTemplateParser simpleTemplateContext() {
        SimpleTemplateParser simpleTemplateParser = new SimpleTemplateParser(
                CacheBuilder.newBuilder().
                expireAfterAccess(1, TimeUnit.DAYS));
        Method method = ReflectionUtils.findMethod(DateUtil.class, "format", Date.class, String.class);
        if (null != method) {
            simpleTemplateParser.registerFunction("dateFormat", method);
        }

        return simpleTemplateParser;
    }

    // ip黑名单处理器
    @Bean
    public InetAddressAccessHandler inetAddressAccessHandler() {
        return new InetAddressAccessHandler();
    }

    // 用户黑名单处理器
    @Bean
    public UserAccessHandler userAccessHandler() {
        return new UserAccessHandler();
    }

    @Bean
    public FilterRegistrationBean accessFilter(){
        // 访问控制过滤器
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.addUrlPatterns("/*");
        bean.setFilter(new AccessFilter());
        bean.setName("accessFilter");
        bean.setOrder(1);
        return bean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.addUrlPatterns("/*");
        // 轨迹跟踪过滤器
        GroupFilter group = new GroupFilter(new TraceFilter());
        group.excludePathPatterns(    //添加不拦截路径
                "/frame/*",
                "/js/*",                    //js静态资源
                "/css/*",                   //css静态资源
                "/public/*",                //public静态资源
                "/script/*",                //script静态资源
                "/error/*"                  //错误页面静态资源
        );
        bean.setFilter(group);
        bean.setName("baseFilter");
        return bean;
    }

}
